<template>
  <div>
    <h2>单步调试</h2>
    <div>
      <pre class="code" v-html="currentCode"></pre>
      <div>
        <button v-if="stepEnv.next" @click="onNext">执行</button>
        <button @click="onRestart">重来</button>
        <pre class="code">{{stepEnv.names}}</pre>
      </div>
    </div>
  </div>
</template>

<script type="text/javascript">
import code from '@/code/program';
import Walker from '@/walker';
import StepWalker from '@/walker/step2';

const acorn = require('acorn');

const tree = acorn.parse(code);

export default {
  data() {
    const stepEnv = {};
    new Walker(StepWalker, stepEnv).walk(tree);

    return {
      stepEnv,
    }
  },
  computed: {
    currentCode() {
      const n = this.stepEnv.currentNode;
      if (n) {
        return code.substr(0, n.start) + `<span class="hightlight">${code.substr(n.start, n.end - n.start)}</span>` + code.substr(n.end);
      }
      return code;
    },
  },
  methods: {
    onNext() {
      const next = this.stepEnv.next;
      this.stepEnv.next = null;
      next();
    },
    onRestart() {
      const tree = acorn.parse(code);
      const stepEnv = {};
      new Walker(StepWalker, stepEnv).walk(tree);
      this.stepEnv = stepEnv;
    },
  },
};
</script>

<style type="text/css">
.hightlight {
  background-color: #d4ffcd;
  color: #555;
  font-weight: bolder;
}
</style>
